package com.woniu.pay.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.woniu.common.constant.Constants;
import com.woniu.common.enums.ExceptionCode;
import com.woniu.common.exception.CustomException;
import com.woniu.pay.config.AlipayConfig;
import com.woniu.pay.service.FinanceService;
import com.woniu34.order.domain.Order;
import com.woniu34.order.api.OrderApi;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class FinanceServiceImpl implements FinanceService {

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private OrderApi orderApi;

    @Value("${alipay.alipay_call_back_ip}")
    private String alipayCallBackUrl;

    @Value("${server.port}")
    private String port;

    @Autowired
    private RabbitTemplate rabbitTemplate;



    @Override
    public String alipay(Long orderId,Long money) {
//        RLock lock = redissonClient.getLock(RedissonConfig.ORDER_LOCK_KEY_PREFIX+orderId);
        try{
//            lock.lock();
            Order order = orderApi.queryById(orderId);
            if(order.getOrderTotalPay()!=money){
                throw new CustomException(ExceptionCode.TOTAL_PAY_INCORRECT);
            }
            if(order.getOrderStatus()!=1){
                throw new CustomException(ExceptionCode.ORDER_STATUS_INCORRECT);
            }

            //获得初始化的AlipayClient
            AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);
            //设置请求参数
            AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
            alipayRequest.setReturnUrl("http://"+alipayCallBackUrl+":"+port+"/finance/alipay/notice");
            alipayRequest.setNotifyUrl("http://"+alipayCallBackUrl+":"+port+"/finance/alipay/notice");
            //商户订单号，商户网站订单系统中唯一订单号，必填
//        String out_trade_no = ""+ UUID.randomUUID();
            String out_trade_no = ""+orderId;

            //付款金额，必填
            String total_amount = ""+money;
            //订单名称，必填
            String subject = "支付宝测试";
            //商品描述，可空
            String body = "商品描述";

            alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                    + "\"total_amount\":\""+ total_amount +"\","
                    + "\"subject\":\""+ subject +"\","
                    + "\"body\":\""+ body +"\","
                    + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

            //请求
            String result = null;
            try {
                result = alipayClient.pageExecute(alipayRequest).getBody();
                System.out.println(result);
            } catch (AlipayApiException e) {
                e.printStackTrace();

            }

            return result;
        }catch (Exception e){

            throw e;
        }finally{
//            lock.unlock();
        }


    }



    @RabbitListener(
            bindings = {
                    @QueueBinding(
                            value = @Queue(name = Constants.MQ_ORDER_PAY_BACK_QUEUE_NAME,
                                    durable = "true"),
                            exchange = @Exchange(name = Constants.MQ_ORDER_PAY_BACK_EXCHANGE_NAME),
                            key = {Constants.MQ_ORDER_PAY_BACK_ROUTING_KEY}
                    )
            }
    )
    public void listenPayback(Map<String,Long> msg ) {

        Long orderId = msg.get("orderId");


        //订单生成失败，调用退款接口
        System.out.println("调用退款接口，给订单："+orderId+ " 退款");
        Map<String,Long> paybackMsg = new HashMap<>();
        paybackMsg.put("orderId",orderId);
        paybackMsg.put("cellphone",13900000000L);

        rabbitTemplate.convertAndSend(Constants.MQ_ORDER_PAY_BACK_CELLPHONE_MSG_EXCHANGE_NAME,Constants.MQ_ORDER_PAY_BACK_CELLPHONE_MSG_ROUTING_KEY,msg);

    }
}
